package com.itheima.reggie.controller;

import com.itheima.reggie.config.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.itheima.reggie.utils.SMSUtils.sendMessage;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private RedisTemplate redisTemplate;
    /**
     * 发送手机短信
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
//        1.获取手机号
        String phone = user.getPhone();
        if (phone!=null){
//        生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("生成的验证码"+code);
//        发送短信
//        SMSUtils.sendMessage("黑马旅游网","SMS_205126318","你自己的手机号",code);
//        将生成的验证码放入到session中
//        session.setAttribute(phone,code);
//            2.优化将验证码放入到Redis
            String key=phone;
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key,code,1, TimeUnit.MINUTES);
//        返回
        }
        return R.success("发送成功");
    }
    /**
     *    http://localhost:8080/user/login
     */
        @PostMapping("/login")
        public R<String>login(@RequestBody Map<String,String>param,HttpSession session){
//            获取手机号和验证码
            String phone = param.get("phone");
            String code = param.get("code");
            //            获取随机生成的验证码
//            String verifyCode = session.getAttribute(phone).toString();
//            优化从redis中获取
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String verifyCode = valueOperations.get(phone).toString();
            User user= userService.login(phone,code,verifyCode);
            session.setAttribute("user",user.getId());
            return R.success("登录成功");
        }
}
